#!/bin/bash

# =====================================================
# 智能协同云图库 - 快速启动脚本
# 创建时间: 2024-01-15
# 版本: 2.0
# 描述: 一键部署和启动智能协同云图库系统
# =====================================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 项目信息
PROJECT_NAME="智能协同云图库"
PROJECT_VERSION="2.0"
PROJECT_DIR=$(cd "$(dirname "$0")/.." && pwd)

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}[$(date '+%Y-%m-%d %H:%M:%S')] ${message}${NC}"
}

print_header() {
    echo -e "${CYAN}"
    echo "======================================================="
    echo "🎨 $PROJECT_NAME v$PROJECT_VERSION"
    echo "🚀 革命性的多模态AI图片处理平台"
    echo "======================================================="
    echo -e "${NC}"
}

print_success() {
    print_message $GREEN "✅ $1"
}

print_info() {
    print_message $BLUE "ℹ️  $1"
}

print_warning() {
    print_message $YELLOW "⚠️  $1"
}

print_error() {
    print_message $RED "❌ $1"
}

# 检查系统要求
check_requirements() {
    print_info "检查系统要求..."
    
    # 检查Java
    if ! command -v java &> /dev/null; then
        print_error "Java未安装，请安装JDK 17或更高版本"
        exit 1
    fi
    
    local java_version=$(java -version 2>&1 | head -n1 | cut -d'"' -f2 | cut -d'.' -f1)
    if [ "$java_version" -lt 17 ]; then
        print_error "Java版本过低，需要JDK 17或更高版本，当前版本: $java_version"
        exit 1
    fi
    print_success "Java版本检查通过: $(java -version 2>&1 | head -n1)"
    
    # 检查Maven
    if ! command -v mvn &> /dev/null; then
        print_error "Maven未安装，请安装Maven 3.6或更高版本"
        exit 1
    fi
    print_success "Maven检查通过: $(mvn -version | head -n1)"
    
    # 检查MySQL
    if ! command -v mysql &> /dev/null; then
        print_warning "MySQL客户端未找到，请确保MySQL服务器已安装并运行"
    else
        print_success "MySQL客户端检查通过"
    fi
    
    # 检查Redis
    if ! command -v redis-cli &> /dev/null; then
        print_warning "Redis客户端未找到，请确保Redis服务器已安装并运行"
    else
        print_success "Redis客户端检查通过"
    fi
}

# 检查端口占用
check_ports() {
    print_info "检查端口占用..."
    
    local ports=(8080 3306 6379)
    for port in "${ports[@]}"; do
        if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
            print_warning "端口 $port 已被占用"
            if [ "$port" = "8080" ]; then
                print_error "应用端口8080被占用，请释放该端口或修改配置"
                exit 1
            fi
        else
            print_success "端口 $port 可用"
        fi
    done
}

# 创建配置文件
create_config() {
    print_info "创建配置文件..."
    
    local config_file="$PROJECT_DIR/src/main/resources/application.yml"
    local template_file="$PROJECT_DIR/src/main/resources/application-template.yml"
    
    if [ ! -f "$config_file" ]; then
        if [ -f "$template_file" ]; then
            cp "$template_file" "$config_file"
            print_success "配置文件已从模板创建"
        else
            print_warning "配置模板文件不存在，创建默认配置"
            cat > "$config_file" << EOF
server:
  port: 8080

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/yu_picture?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
  
  redis:
    host: localhost
    port: 6379
    database: 0
  
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: false

logging:
  level:
    com.yupi.yupicturebackend: INFO
  file:
    name: logs/yu-picture.log
EOF
        fi
        print_success "配置文件创建完成: $config_file"
    else
        print_info "配置文件已存在，跳过创建"
    fi
}

# 初始化数据库
init_database() {
    print_info "初始化数据库..."
    
    # 检查数据库连接
    read -p "请输入MySQL root密码: " -s mysql_password
    echo
    
    if mysql -u root -p$mysql_password -e "SELECT 1" >/dev/null 2>&1; then
        print_success "数据库连接成功"
        
        # 执行初始化脚本
        local init_script="$PROJECT_DIR/sql/init_database.sql"
        if [ -f "$init_script" ]; then
            print_info "执行数据库初始化脚本..."
            mysql -u root -p$mysql_password < "$init_script"
            print_success "数据库初始化完成"
        else
            print_error "数据库初始化脚本不存在: $init_script"
            exit 1
        fi
    else
        print_error "数据库连接失败，请检查MySQL服务和密码"
        exit 1
    fi
}

# 构建项目
build_project() {
    print_info "构建项目..."
    
    cd "$PROJECT_DIR"
    
    # 清理并编译
    print_info "清理项目..."
    mvn clean >/dev/null 2>&1
    
    print_info "编译项目..."
    if mvn compile -q; then
        print_success "项目编译成功"
    else
        print_error "项目编译失败"
        exit 1
    fi
    
    # 运行测试
    print_info "运行测试..."
    if mvn test -q; then
        print_success "测试通过"
    else
        print_warning "部分测试失败，但继续构建"
    fi
    
    # 打包
    print_info "打包项目..."
    if mvn package -DskipTests -q; then
        print_success "项目打包成功"
    else
        print_error "项目打包失败"
        exit 1
    fi
}

# 启动应用
start_application() {
    print_info "启动应用..."
    
    cd "$PROJECT_DIR"
    
    # 创建日志目录
    mkdir -p logs
    
    # 启动应用
    print_info "正在启动智能协同云图库..."
    
    # 后台启动
    nohup java -jar target/yu-picture-backend-*.jar \
        --spring.profiles.active=prod \
        > logs/startup.log 2>&1 &
    
    local app_pid=$!
    echo $app_pid > yu-picture.pid
    
    print_info "应用启动中，PID: $app_pid"
    
    # 等待应用启动
    local max_wait=60
    local wait_time=0
    
    while [ $wait_time -lt $max_wait ]; do
        if curl -s http://localhost:8080/actuator/health >/dev/null 2>&1; then
            print_success "应用启动成功！"
            break
        fi
        
        sleep 2
        wait_time=$((wait_time + 2))
        print_info "等待应用启动... ($wait_time/$max_wait 秒)"
    done
    
    if [ $wait_time -ge $max_wait ]; then
        print_error "应用启动超时，请检查日志: logs/startup.log"
        exit 1
    fi
}

# 显示启动信息
show_startup_info() {
    print_header
    
    echo -e "${GREEN}"
    echo "🎉 智能协同云图库启动成功！"
    echo ""
    echo "📊 系统信息:"
    echo "   • 应用地址: http://localhost:8080"
    echo "   • API文档: http://localhost:8080/swagger-ui.html"
    echo "   • 健康检查: http://localhost:8080/actuator/health"
    echo "   • 日志文件: $PROJECT_DIR/logs/"
    echo ""
    echo "🚀 核心功能:"
    echo "   • AI图片生成: POST /api/ai/generation/create"
    echo "   • NFT铸造: POST /api/nft/mint"
    echo "   • 智能搜索: GET /api/search/intelligent"
    echo "   • 游戏创建: POST /api/game/puzzle/create"
    echo "   • 协作项目: POST /api/collaboration/project/create"
    echo ""
    echo "🔧 管理命令:"
    echo "   • 停止应用: ./scripts/stop.sh"
    echo "   • 查看日志: tail -f logs/yu-picture.log"
    echo "   • 重启应用: ./scripts/restart.sh"
    echo -e "${NC}"
    
    # 创建停止脚本
    cat > "$PROJECT_DIR/scripts/stop.sh" << 'EOF'
#!/bin/bash
if [ -f yu-picture.pid ]; then
    PID=$(cat yu-picture.pid)
    if kill -0 $PID 2>/dev/null; then
        kill $PID
        echo "应用已停止 (PID: $PID)"
        rm yu-picture.pid
    else
        echo "应用未运行"
        rm yu-picture.pid
    fi
else
    echo "PID文件不存在，应用可能未运行"
fi
EOF
    chmod +x "$PROJECT_DIR/scripts/stop.sh"
    
    # 创建重启脚本
    cat > "$PROJECT_DIR/scripts/restart.sh" << 'EOF'
#!/bin/bash
echo "重启智能协同云图库..."
./scripts/stop.sh
sleep 3
./scripts/quick-start.sh --skip-init
EOF
    chmod +x "$PROJECT_DIR/scripts/restart.sh"
}

# 主函数
main() {
    print_header
    
    # 解析命令行参数
    local skip_init=false
    local skip_build=false
    
    while [[ $# -gt 0 ]]; do
        case $1 in
            --skip-init)
                skip_init=true
                shift
                ;;
            --skip-build)
                skip_build=true
                shift
                ;;
            --help|-h)
                echo "用法: $0 [选项]"
                echo "选项:"
                echo "  --skip-init   跳过数据库初始化"
                echo "  --skip-build  跳过项目构建"
                echo "  --help, -h    显示帮助信息"
                exit 0
                ;;
            *)
                print_error "未知选项: $1"
                exit 1
                ;;
        esac
    done
    
    # 执行启动流程
    check_requirements
    check_ports
    create_config
    
    if [ "$skip_init" = false ]; then
        init_database
    else
        print_info "跳过数据库初始化"
    fi
    
    if [ "$skip_build" = false ]; then
        build_project
    else
        print_info "跳过项目构建"
    fi
    
    start_application
    show_startup_info
}

# 错误处理
trap 'print_error "脚本执行失败，请检查错误信息"; exit 1' ERR

# 执行主函数
main "$@"
